<template>
  <Card
    title="列表行样式"
    :bordered="false"
    :head-style="headStyle"
    :loading="loading"
    class="row-style"
  >
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" @click="handleSave"> 保存 </a-button>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'cond'">
          <a-button
            :type="record[column.key] && record[column.key].length ? 'primary' : 'default'"
            @click="handleConfiguration(column.key, index)"
          >
            <SettingOutlined title="配置" />
          </a-button>
        </template>
        <template v-if="column.key === 'isBold'">
          <Switch
            v-model:checked="record['isBold']"
            checked-children="是"
            un-checked-children="否"
          />
        </template>
        <template v-if="column.key === 'backgroundColor'">
          <ColorPicker format="rgba" v-model:value="record[column.key]" />
        </template>
        <template v-if="column.key === 'color'">
          <ColorPicker format="rgba" v-model:value="record[column.key]" />
        </template>
        <template v-if="column.key === 'promptIcon'">
          <TreeSelect
            style="width: 100%"
            :tree-data="imgeLists"
            :show-search="true"
            treeNodeFilterProp="label"
            v-model:value="record[column.key]"
          >
            <template #title="item">
              <div class="flex"
                ><Image :src="item.img" style="" /><div class="ml-3">{{ item.label }}</div></div
              >
            </template>
          </TreeSelect>
        </template>
      </template>
      <template #action="{ index }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              tooltip: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: handleDelete.bind(null, index),
              },
            },
          ]"
        />
        <div></div>
      </template>
    </BasicTable>

    <ConfigurationModal
      @register="registerModalConfiguration"
      @success="handleSuccessConfiguration"
      popupContainer=".row-style"
    />
  </Card>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { TreeSelect, Card, Image, Switch } from 'ant-design-vue';
  import { isArray } from '/@/utils/is';
  import {
    getVisualGetPromptIcon,
    getVisualGetRowProps,
    getVisualUpdateRowProps,
  } from '/@/api/module/module';
  import { useUserStore } from '/@/store/modules/user';
  import { SettingOutlined } from '@ant-design/icons-vue';
  import ColorPicker from '/@/components/ColorPicker/src/ColorPicker.vue';
  import { useModal } from '/@/components/Modal';
  import ConfigurationModal from '../../configuration/index';

  export default defineComponent({
    // eslint-disable-next-line vue/component-definition-name-casing
    components: {
      BasicTable,
      TableAction,
      TreeSelect,
      Card,
      Image,
      SettingOutlined,
      Switch,
      ColorPicker,
      ConfigurationModal,
    },
    props: {
      moduleCode: {
        type: String,
        default: '',
      },
      headStyle: {
        type: Object,
        default: () => {
          return {};
        },
      },
      formGetFieldsData: {
        type: Array as PropType<Array<any>>,
        default: () => [],
      },
    },
    setup(props) {
      const { createMessage, createConfirm } = useMessage();
      const loading = ref(false);
      const imgeLists = ref<Recordable[]>([]);
      const getVisualGetRowPropsData = async () => {
        const res = await getVisualGetRowProps({ moduleCode: props.moduleCode });
        const data = res.rowProps ? JSON.parse(res.rowProps) : [];
        setTableData(data);
      };
      const fetch = async () => {
        nextTick().then(() => {
          getVisualGetPromptIconData();
          getVisualGetRowPropsData();
        });
      };
      onMounted(fetch);

      const columns = ref([
        {
          title: '条件',
          dataIndex: 'cond',
          key: 'cond',
        },
        {
          title: '背景颜色',
          dataIndex: 'backgroundColor',
          key: 'backgroundColor',
        },
        {
          title: '文字颜色',
          dataIndex: 'color',
          key: 'color',
        },
        {
          title: '是否加粗',
          dataIndex: 'isBold',
          key: 'isBold',
        },
        {
          title: '图标',
          dataIndex: 'promptIcon',
          key: 'promptIcon',
        },
      ]);

      const [registerTable, { reload, setProps, getDataSource, setTableData }] = useTable({
        title: '',
        api: getVisualGetRowProps,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: [],
          autoSubmitOnEnter: true,
        },
        useSearchForm: false,
        showTableSetting: false,
        showIndexColumn: true,
        immediate: false,
        searchInfo: {
          moduleCode: props.moduleCode,
        }, //额外的参数
        // afterFetch: (data) => {
        //   console.log('data', data);
        //   const newData = data;
        //   if (isArray(newData)) {
        //     newData.forEach((item) => {

        //     });
        //     setTableData(newData);
        //   }
        // },
        bordered: true,
        indexColumnProps: { width: 50 },
        canResize: false,
        rowKey: 'id',
        actionColumn: {
          width: 200,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      //新增
      const handleCreate = () => {
        console.log('getDataSource', getDataSource());
        let data = getDataSource() || [];
        data.push({ cond: '', backgroundColor: '', isBold: '', promptIcon: '', color: '' });
        setTableData(data);
      };

      async function handleDelete(index) {
        try {
          let data = getDataSource() || [];
          data.splice(index, 1);
          setTableData(data);
        } catch (err) {
          console.error(err);
        } finally {
          handleSetProps(false);
        }
      }

      function handleSuccess() {
        getVisualGetRowPropsData();
      }

      const handleSetProps = (bool: boolean) => {
        setProps({ loading: bool });
      };

      const userStore = useUserStore();
      const serverInfo = userStore.getServerInfo;
      //获取初始化数据
      const getVisualGetPromptIconData = async () => {
        const res = await getVisualGetPromptIcon({ moduleCode: props.moduleCode });
        let options = res.icons;
        imgeLists.value = [];
        if (!isArray(options)) {
          imgeLists.value = [];
        } else {
          if (options && options.length > 0) {
            options.forEach((item) => {
              const obj = {};
              obj['value'] = item;
              obj['img'] = item
                ? serverInfo.rootPath + (item && item.startsWith('/') ? item : `/${item}`)
                : '';
              let label = item.substring(item.lastIndexOf('/') + 1);
              obj['label'] = label;
              obj['children'] = [];
              imgeLists.value.push(obj);
            });
            console.log('imgeLists', imgeLists.value);
          }
        }
      };
      let currentIndex = 0;
      const [registerModalConfiguration, { openModal: openConfiguration }] = useModal();
      //配置
      const handleConfiguration = (field, index) => {
        currentIndex = index;
        let data = getDataSource() || [];
        openConfiguration(true, {
          type: field,
          list: data[currentIndex][field] || [],
          formGetFieldsData: props.formGetFieldsData,
        });
      };
      //配置回调
      const handleSuccessConfiguration = ({ field, value }) => {
        console.log('handleSuccessConfiguration', value);
        let data = getDataSource() || [];
        data[currentIndex][field] = value;
        setTableData(data);
      };

      const handleSave = async () => {
        const data = getDataSource() || [];
        console.log('data', data);
        try {
          const params = {
            rowProps: data.length ? JSON.stringify(data) : '',
            moduleCode: props.moduleCode,
          };
          handleSetProps(true);
          await getVisualUpdateRowProps(params);
          createMessage.success('操作成功');
          handleSuccess();
        } catch (err) {
          console.error(err);
        } finally {
          handleSetProps(false);
        }
      };
      return {
        registerTable,
        handleDelete,
        handleSuccess,
        handleCreate,
        loading,
        imgeLists,
        registerModalConfiguration,
        handleConfiguration,
        handleSuccessConfiguration,
        handleSave,
      };
    },
  });
</script>
<style scoped>
  :deep(.ant-table-cell) {
    overflow: visible !important;
  }
  :deep(.ant-table-content) {
    overflow: unset !important;
  }
</style>
